
package com.hdoit.ares.web.share.apis;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hdoit.ares.logical.acc.model.WithdrawParam;
import com.hdoit.ares.logical.acc.service.IGoldenBeanDetailService;
import com.hdoit.ares.logical.acc.service.IWithdrawParamService;
import com.hdoit.ares.logical.acti.model.Activity;
import com.hdoit.ares.logical.acti.service.IActivityService;
import com.hdoit.ares.logical.cust.model.CustCollection;
import com.hdoit.ares.logical.cust.model.CustFootprint;
import com.hdoit.ares.logical.cust.service.ICustCollectionService;
import com.hdoit.ares.logical.cust.service.ICustFootprintService;
import com.hdoit.ares.logical.official.model.Artical;
import com.hdoit.ares.logical.official.model.ArticalClassify;
import com.hdoit.ares.logical.official.model.ArticalComment;
import com.hdoit.ares.logical.official.model.ArticalPraise;
import com.hdoit.ares.logical.official.model.PraiseAndGlance;
import com.hdoit.ares.logical.official.service.IArticalClassifyService;
import com.hdoit.ares.logical.official.service.IArticalCommentService;
import com.hdoit.ares.logical.official.service.IArticalPraiseService;
import com.hdoit.ares.logical.official.service.IArticalService;
import com.hdoit.ares.logical.official.service.IPraiseAndGlanceService;
import com.hdoit.ares.logical.viewmodel.official.ArticalClassifySearch;
import com.hdoit.ares.logical.viewmodel.official.ArticalCommentSearch;
import com.hdoit.ares.logical.viewmodel.official.ArticalSearch;
import com.hdoit.ares.selfcommon.enums.official.TypeOfPraise;
import com.hdoit.ares.selfcommon.utils.EmojiUtil;
import com.hdoit.ares.selfcommon.utils.GetClassPropertyName;
import com.tennetcn.common.enums.ModelStatus;
import com.tennetcn.common.logical.file.model.OssFileInfo;
import com.tennetcn.common.logical.file.service.IOssFileInfoService;
import com.tennetcn.common.utils.CommonUtils;
import com.tennetcn.common.utils.DateUtils;
import com.tennetcn.component.webapi.BaseApi;
import com.tennetcn.component.webapi.ResponseModel;
import com.tennetcn.component.webapi.ResponseStatus;
import com.tennetcn.web.cbase.ApiAuthPassport;
import com.tennetcn.web.cbase.AuthPassport;


@Controller
@RequestMapping(value = "/api/v1/cloudClass/",method = {RequestMethod.GET,RequestMethod.POST},produces="application/json;charset=utf-8")
@Api(value="/api/v1/cloudClass/")
@CrossOrigin(origins = "*",maxAge = 3600)
public class CloudClassApi extends BaseApi{
	
	
	private IArticalService articalService;
	private IArticalClassifyService articalClassifyService;
	private IPraiseAndGlanceService praiseAndGlanceService;
	private IArticalCommentService articalCommentService;
	private IArticalPraiseService articalPraiseService;
	private IWithdrawParamService withdrawParamService;

	private IActivityService activityService;
	private IGoldenBeanDetailService goldenBeanDetailService;

	private ICustFootprintService custFootprintService;
	private ICustCollectionService custCollectionService;
	private IOssFileInfoService ossFileInfoService;


	public ICustCollectionService getCustCollectionService() {
		return custCollectionService;
	}
	@Resource
	public void setCustCollectionService(
			ICustCollectionService custCollectionService) {
		this.custCollectionService = custCollectionService;
	}
	public ICustFootprintService getCustFootprintService() {
		return custFootprintService;
	}
	@Resource
	public void setCustFootprintService(ICustFootprintService custFootprintService) {
		this.custFootprintService = custFootprintService;
	}
	public IArticalService getArticalService() {
		return articalService;
	}
	@Resource
	public void setArticalService(IArticalService articalService) {
		this.articalService = articalService;
	}
	
	

	public IArticalClassifyService getArticalClassifyService() {
		return articalClassifyService;
	}
	@Resource
	public void setArticalClassifyService(IArticalClassifyService articalClassifyService) {
		this.articalClassifyService = articalClassifyService;
	}


	public IPraiseAndGlanceService getPraiseAndGlanceService() {
		return praiseAndGlanceService;
	}
	@Resource
	public void setPraiseAndGlanceService(IPraiseAndGlanceService praiseAndGlanceService) {
		this.praiseAndGlanceService = praiseAndGlanceService;
	}

	
	public IArticalCommentService getArticalCommentService() {
		return articalCommentService;
	}
	@Resource
	public void setArticalCommentService(IArticalCommentService articalCommentService) {
		this.articalCommentService = articalCommentService;
	}
	
	public IArticalPraiseService getArticalPraiseService() {
		return articalPraiseService;
	}
	@Resource
	public void setArticalPraiseService(IArticalPraiseService articalPraiseService) {
		this.articalPraiseService = articalPraiseService;
	}

	
	public IActivityService getActivityService() {
		return activityService;
	}
	@Resource
	public void setActivityService(IActivityService activityService) {
		this.activityService = activityService;
	}

    
	public IGoldenBeanDetailService getGoldenBeanDetailService() {
		return goldenBeanDetailService;
	}
	@Resource
	public void setGoldenBeanDetailService(IGoldenBeanDetailService goldenBeanDetailService) {
		this.goldenBeanDetailService = goldenBeanDetailService;
	}
	
	
	
	public IOssFileInfoService getOssFileInfoService() {
		return ossFileInfoService;
	}
	@Resource
	public void setOssFileInfoService(IOssFileInfoService ossFileInfoService) {
		this.ossFileInfoService = ossFileInfoService;
	}



	public IWithdrawParamService getWithdrawParamService() {
		return withdrawParamService;
	}
	@Resource
	public void setWithdrawParamService(IWithdrawParamService withdrawParamService) {
		this.withdrawParamService = withdrawParamService;
	}



	private final String indexApi = "index";
	private final String informationApi = "information";
	private final String informationDetailedApi = "informationDetailed";
	private final String postMessageApi = "postMessage";
	private final String articalCommentApi = "articalComment";
	private final String praiseApi = "praise";
	private final String videoDetailedApi = "videoDetailed";
	private final String commentDetailedApi = "commentDetailed";
	
	@ApiAuthPassport
	@ResponseBody
	@RequestMapping(value = indexApi)
	@ApiOperation(notes= indexApi,httpMethod = "POST" ,value = "云课堂首页")
	public String index(){
		ResponseModel rm = new ResponseModel();
		List<String> articalClassifyParams = new GetClassPropertyName<ArticalClassify>().getClassName(new ArticalClassify());
		List<String> articalParams = new GetClassPropertyName<Artical>().getClassName(new Artical());
		List<String> activityParams = new GetClassPropertyName<Activity>().getClassName(new Activity());
		
		
		List<ArticalClassify> articalClassifys = articalClassifyService.queryList("areas/wechat/share/cloudClass");
		articalClassifys = sortForArticalClassify(articalClassifys);
		rm.putList("articalClassifys", articalClassifys,articalClassifyParams);
		
		//找出热点资讯
		List<Artical> articals = articalService.findHot(articalClassifys);
		for(Artical artical:articals){
			artical.setImgUrl(getRealUrl(artical.getImgUrl()));
		}
		rm.putList("articals", articals,articalParams);
		
		//找出成功分享的资讯
		ArticalClassifySearch articalClassifySearch = new ArticalClassifySearch();
		articalClassifySearch.setFunctionURL("areas/wechat/share/information/successShare");
		ArticalClassify articalClassify = articalClassifyService.queryModel(articalClassifySearch);
		
		ArticalSearch articalSearch = new ArticalSearch();
		articalSearch.setTypeId(articalClassify.getId());
		Artical artical = articalService.queryList(articalSearch).get(0);
		artical.setImgUrl(getRealUrl(artical.getImgUrl()));
		rm.putObj("artical", artical, articalParams);
		
		//活动任务轮播
		List<Activity> activitys = activityService.queryListHotActivitys();
		rm.putList("activitys", activitys,activityParams);
		
		rm.setStatus(ResponseStatus.success);
		rm.setMessage("ok");

		return rm.toJson();
	}
	
	
	@ResponseBody
	@RequestMapping(value = informationDetailedApi)
	@ApiOperation(notes= informationDetailedApi,httpMethod = "POST" ,value = "文章详情页面")
	public String informationDetailed(@ApiParam("文章id,必填") @RequestParam(value="id",required=true)String id){
		ResponseModel rm = new ResponseModel();
		
		//查出分页的页数
		WithdrawParam pageSize = withdrawParamService.queryModelByHelpCode("pageSize");
		
		//反射得到各个类的属性
		List<String> praiseAndGlanceParams = new GetClassPropertyName<PraiseAndGlance>().getClassName(new PraiseAndGlance());
		List<String> articalParams = new GetClassPropertyName<Artical>().getClassName(new Artical());
		List<String> articalPraiseParams = new GetClassPropertyName<ArticalPraise>().getClassName(new ArticalPraise());
/*		List<String> articalCommentParams = new GetClassPropertyName<ArticalComment>().getClassName(new ArticalComment());
*/		List<String> custCollectionParams = new GetClassPropertyName<CustCollection>().getClassName(new CustCollection());

		
		String customerId = getLoginId();

		Artical artical = articalService.queryModel(id);
		
		
		
		
		rm.putObj("artical", artical, articalParams);

		//点赞次数和浏览次数
		PraiseAndGlance praiseAndGlance = praiseAndGlanceService.queryModel(artical.getId(), TypeOfPraise.Medio);
		praiseAndGlance.setGlanceCount(praiseAndGlance.getGlanceCount() + 1);
		System.err.println("检测是否真的发生了变化" + praiseAndGlance.getGlanceCount());
		
		praiseAndGlanceService.updateModel(praiseAndGlance);
		rm.putObj("praiseAndGlance", praiseAndGlance, praiseAndGlanceParams);
		
		//是否点过赞
		ArticalPraise articalPraise = articalPraiseService.queryModel(id,TypeOfPraise.Medio,customerId);
		if(articalPraise != null){
			rm.putObj("articalPraise", articalPraise, articalPraiseParams);
		}else{
			rm.putObj("articalPraise", new ArticalPraise(), articalPraiseParams);
		}
		
		
		//评论
	/*	ArticalCommentSearch search = new ArticalCommentSearch();
		search.setArticalId(id);
		search.setPraiseCutomerId(customerId);
		search.setPageSize(pageSize.getParam());
		List<ArticalComment> articalComments = articalCommentService.queryListBySearch(search);
		if(articalComments == null){
			articalComments = new ArrayList<>();
		}
		rm.putList("articalComments", articalComments, articalCommentParams);*/
		
		
		/*收藏*/
		CustCollection custCollection=custCollectionService.selectCustCollection(artical.getId(),customerId);
		if(custCollection != null){
			rm.put("custCollection", "collected");
		}else{
			rm.put("custCollection", "uncCollect");
		}
		
		
		//足迹
		CustFootprint custFootprint=custFootprintService.selectCustFootprint(artical.getId(),customerId);
		if(custFootprint == null){
			custFootprint = new CustFootprint();
			custFootprint.setId(CommonUtils.getKeyId());
			custFootprint.setType(artical.getMedioType());
			custFootprint.setThingId(artical.getId());
			custFootprint.setCustId(customerId);
			custFootprint.setBrowseDate(DateUtils.getCurrent());
			
			custFootprint.setModelStatus(ModelStatus.add);
		}else{
			custFootprint.setBrowseDate(DateUtils.getCurrent());
			
			custFootprint.setModelStatus(ModelStatus.update);
		}
		custFootprintService.applyChange(custFootprint);
		
		rm.setStatus(ResponseStatus.success);
		rm.setMessage("ok");
		
		

		return rm.toJson();
	}
	
	@ResponseBody
	@RequestMapping(value = videoDetailedApi)
	@ApiOperation(notes= videoDetailedApi,httpMethod = "POST" ,value = "视频详情页面")
	public String videoDetailed(@ApiParam("视频id,必填") @RequestParam(value="id",required=true)String id){
		ResponseModel rm = new ResponseModel();
		
		//查出分页的页数
		WithdrawParam pageSize = withdrawParamService.queryModelByHelpCode("pageSize");
		
		//反射得到各个类的属性
		List<String> praiseAndGlanceParams = new GetClassPropertyName<PraiseAndGlance>().getClassName(new PraiseAndGlance());
		List<String> articalParams = new GetClassPropertyName<Artical>().getClassName(new Artical());
		List<String> articalPraiseParams = new GetClassPropertyName<ArticalPraise>().getClassName(new ArticalPraise());
/*		List<String> articalCommentParams = new GetClassPropertyName<ArticalComment>().getClassName(new ArticalComment());
*/		List<String> custCollectionParams = new GetClassPropertyName<CustCollection>().getClassName(new CustCollection());

		
		String customerId = getLoginId();

		Artical artical = articalService.queryModel(id);
		artical.setImgUrl(getRealUrl(artical.getImgUrl()));
		artical.setVideoUrl(getRealUrl(artical.getVideoUrl()));
		rm.putObj("artical", artical, articalParams);

		//点赞次数和浏览次数
		PraiseAndGlance praiseAndGlance = praiseAndGlanceService.queryModel(artical.getId(), TypeOfPraise.Medio);
		praiseAndGlance.setGlanceCount(praiseAndGlance.getGlanceCount() + 1);
		System.err.println("检测是否真的发生了变化" + praiseAndGlance.getGlanceCount());
		
		praiseAndGlanceService.updateModel(praiseAndGlance);
		rm.putObj("praiseAndGlance", praiseAndGlance, praiseAndGlanceParams);
		
		//是否点过赞
		ArticalPraise articalPraise = articalPraiseService.queryModel(id,TypeOfPraise.Medio,customerId);
		if(articalPraise != null){
			rm.putObj("articalPraise", articalPraise, articalPraiseParams);
		}else{
			rm.putObj("articalPraise", new ArticalPraise(), articalPraiseParams);
		}
		
		
		
		//评论
		/*ArticalCommentSearch search = new ArticalCommentSearch();
		search.setArticalId(id);
		search.setPraiseCutomerId(customerId);
		search.setPageSize(pageSize.getParam());
		List<ArticalComment> articalComments = articalCommentService.queryListBySearch(search);
		if(articalComments == null){
			articalComments = new ArrayList<>();
		}
		rm.putList("articalComments", articalComments, articalCommentParams);
		*/
		
		/*收藏*/
		CustCollection custCollection=custCollectionService.selectCustCollection(artical.getId(),customerId);
		if(custCollection != null){
			rm.put("custCollection", "collected");
		}else{
			rm.put("custCollection", "unCollect");
		}
		
		//足迹
		CustFootprint custFootprint=custFootprintService.selectCustFootprint(artical.getId(),customerId);
		if(custFootprint == null){
			custFootprint = new CustFootprint();
			custFootprint.setId(CommonUtils.getKeyId());
			custFootprint.setType(artical.getMedioType());
			custFootprint.setThingId(artical.getId());
			custFootprint.setCustId(customerId);
			custFootprint.setBrowseDate(DateUtils.getCurrent());
			
			custFootprint.setModelStatus(ModelStatus.add);
		}else{
			custFootprint.setBrowseDate(DateUtils.getCurrent());
			
			custFootprint.setModelStatus(ModelStatus.update);
		}
		custFootprintService.applyChange(custFootprint);
		
		rm.setStatus(ResponseStatus.success);
		rm.setMessage("ok");
		
		

		return rm.toJson();
	}
	
	
	@ResponseBody
	@RequestMapping(value = articalCommentApi)
	@ApiOperation(notes= articalCommentApi,httpMethod = "POST" ,value = "评论的下拉刷新和上拉加载")
	public String articalComment(@ApiParam("文章的id,必选") @RequestParam(value="articalId",required=true)String articalId,
			@ApiParam("评论分页的时候需要传的数据，1代表第一页。不传默认第一页") @RequestParam(value="pageNo",required=false)String pageNo,
			@ApiParam("评论分页的时候需要传的数据,每一页最后一条评论的时间，上拉刷新必备") @RequestParam(value="beforeTime",required=false)String beforeTime){
		
		String customerId = getLoginId();
		
		//查出分页的页数
		WithdrawParam pageSize = withdrawParamService.queryModelByHelpCode("pageSize");
		
		
		ResponseModel rm = new ResponseModel();
		List<String> articalCommentParams = new GetClassPropertyName<ArticalComment>().getClassName(new ArticalComment());
		
	
		ArticalCommentSearch search = new ArticalCommentSearch();
		search.setArticalId(articalId);
		search.setPraiseCutomerId(customerId);
		search.setPageSize(pageSize.getParam());
		if(!StringUtils.isEmpty(pageNo)){
			search.setPageNo(Integer.valueOf(pageNo));
		}
		if(!StringUtils.isEmpty(beforeTime)){
			search.setBeforeTime(DateUtils.parseDateTime(beforeTime));
		}
		
		
		
		
		List<ArticalComment> articalComments = articalCommentService.queryListBySearch(search);
		if(articalComments != null){
			for(ArticalComment articalComment:articalComments){
				articalComment.setComment(EmojiUtil.emojiConverterUnicodeStr(articalComment.getComment()));
			}
			
		}
		rm.putList("articalComments", articalComments, articalCommentParams);
		
		
		rm.setStatus(ResponseStatus.success);
		rm.setMessage("ok");

		return rm.toJson();
	}
	
	@ApiAuthPassport
	@ResponseBody
	@RequestMapping(value = informationApi)
	@ApiOperation(notes= informationApi,httpMethod = "POST" ,value = "产品知识、创客技巧、保险知识和资讯分享的入口")
	public String information(@ApiParam("文章的分类,可传4种字符串分别是：skill、productKnowledge、shareInformation、insuranceKnownledge,必选") @RequestParam(value="typeName",required=true)String typeName,
			@ApiParam("文章分页的时候需要传的数据，1代表第一页。不传默认第一页") @RequestParam(value="pageNo",required=false)String pageNo){
		
		//查出分页的页数
		WithdrawParam pageSize = withdrawParamService.queryModelByHelpCode("pageSize");
		
		
		ResponseModel rm = new ResponseModel();
		List<String> articalParams = new GetClassPropertyName<Artical>().getClassName(new Artical());
		
		ArticalClassifySearch articalClassifySearch = new ArticalClassifySearch();
		articalClassifySearch.setFunctionURL("areas/wechat/share/information/" + typeName);
		ArticalClassify articalClassify = articalClassifyService.queryModel(articalClassifySearch);
		
		ArticalSearch articalSearch = new ArticalSearch();
		if(!StringUtils.isEmpty(pageNo)){
			articalSearch.setPageNo(Integer.valueOf(pageNo));
		}
		articalSearch.setPageSize(pageSize.getParam());
		
		articalSearch.setTypeId(articalClassify.getId());
		List<Artical> articals = articalService.queryArticals(articalSearch);
		for(Artical artical:articals){
			artical.setImgUrl(getRealUrl(artical.getImgUrl()));
		}
		
		
		rm.putList("articals", articals, articalParams);
		rm.setStatus(ResponseStatus.success);
		rm.setMessage("ok");

		return rm.toJson();
	}
	

	@ResponseBody
	@RequestMapping(value = praiseApi)
	@ApiOperation(notes= praiseApi,httpMethod = "POST" ,value = "文章、视频和评论的点赞")
	public String praise(@ApiParam("文章、视频传medio,评论传comment,必选") @RequestParam(value="typeName",required=true)String typeName,
			@ApiParam("被点赞对象的id,必选") @RequestParam(value="id",required=true)String id){

		ResponseModel rm = new ResponseModel();
		
		String customerId = getLoginId();
		if(TypeOfPraise.Medio.equals(typeName)){
			articalPraiseService.toThumb(id.trim(),TypeOfPraise.Medio,customerId);
		}else if(TypeOfPraise.Comment.equals(typeName)){
			articalPraiseService.toThumb(id.trim(),TypeOfPraise.Comment,customerId);
		}else{
			rm.setMessage("传入的typeName有误，没有该类型");
			rm.setStatus(ResponseStatus.dataError);
			return rm.toJson();
		}
		
		
		rm.setStatus(ResponseStatus.success);
		rm.setMessage("ok");

		return rm.toJson();
	}
	
	@ResponseBody
	@RequestMapping(value = postMessageApi)
	@ApiOperation(notes= postMessageApi,httpMethod = "POST" ,value = "发表评论和回复评论")
	public String postMessage(@ApiParam("评论的内容，必填") @RequestParam(value="content",required=true)String content,
			@ApiParam("文章的id,必选") @RequestParam(value="articalId",required=true)String articalId,
			@ApiParam("被评论的人的id,只有是回复的时候才传") @RequestParam(value="replyedId",required=false)String replyedId){

		ResponseModel rm = new ResponseModel();
		
		
		List<String> articalCommentParams = new GetClassPropertyName<ArticalComment>().getClassName(new ArticalComment());
		
		String customerId = getLoginId();
		ArticalComment articalComment = articalCommentService.addModel(EmojiUtil.emojiConverterToAlias(content), articalId, customerId,replyedId);
		rm.putObj("articalComment", articalComment, articalCommentParams);
		
		rm.setStatus(ResponseStatus.success);
		rm.setMessage("ok");

		return rm.toJson();
	}
	
	
	@ResponseBody
	@RequestMapping(value = commentDetailedApi)
	@ApiOperation(notes= commentDetailedApi,httpMethod = "POST" ,value = "进入评论的详情页面")
	public String commentDetailed(@ApiParam("评论的id，必填") @RequestParam(value="id",required=true)String id){

		ResponseModel rm = new ResponseModel();
		
		List<String> articalCommentParams = new GetClassPropertyName<ArticalComment>().getClassName(new ArticalComment());
		
		String customerId = getLoginId();
		
		ArticalCommentSearch articalCommentSearch = new ArticalCommentSearch();
		articalCommentSearch.setId(id);
		articalCommentSearch.setPraiseCutomerId(customerId);
		ArticalComment articalComment = articalCommentService.queryModel(articalCommentSearch);
		
		rm.putObj("articalComment", articalComment, articalCommentParams);
		rm.setStatus(ResponseStatus.success);
		rm.setMessage("ok");

		return rm.toJson();
	}
	
	
	
	 //排序
    public List<ArticalClassify> sortForArticalClassify(List<ArticalClassify> articalClassifys){
    	if(articalClassifys != null && articalClassifys.size() >= 2){
    		/*Collections.sort(articalClassifys, new Comparator<ArticalClassify>(){
				@Override
				public int compare(ArticalClassify o1, ArticalClassify o2) {	
					return o1.getSortCode() - o2.getSortCode();
				}	
    		});*/
    		//与上面等价，lambda表达式处理
    		Collections.sort(articalClassifys, Comparator.comparing(ArticalClassify::getSortCode));
    	}
    	return articalClassifys;
    }
    
    //将图片地址变为真实腾讯云上的地址
    public String getRealUrl(String url){
    	if(StringUtils.isEmpty(url)){
    		return null;
    	}
    	/*真实的图片路径前缀*/
		String preUrl = "http://putiyoli-1254043822.cosgz.myqcloud.com";
		
		/*测试的图片路径前缀*/
		/*String preUrl = "http://test-1254043822.cosgz.myqcloud.com";*/	
    	OssFileInfo ossFileInfo = ossFileInfoService.queryModel(url);
    
    	
    	
    	return preUrl + ossFileInfo.getFilename();
    }
    
  
    
   
}
